package com.api.common.language;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.api.common.config.ApiConfig;
import com.api.common.utils.StringUtils;
import lombok.Data;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Data
@Component
public class LanguageBean implements CommandLineRunner {
    private static final Logger log = LoggerFactory.getLogger(LanguageBean.class);
    //    @Value("${language.initLang}")
//    private static String initLang = "zh-CN";
    private static String initLang = ApiConfig.getInitLang();
    private static Map<String, JSONObject> langItemMap;
    //    @Value("${language.charsetName}")
//    private String charsetName;
    private String charsetName = ApiConfig.getCharsetName();
//    @Value("${language.filePath}")
//    private String filePath;

    @Autowired
    private ApiConfig apiConfig;

    public LanguageBean() {
    }

    public static String getInitLang() {

//        return (initLang == null) ? ApiConfig.getInitLang() : initLang;
        return initLang;
    }

    /**
     * 通过 HttpHeader 获取语种key，调用对应翻译
     *
     * @param langKey
     * @param descKey
     * @return
     * @throws Exception
     */
    public static String getLangJsonObj(String langKey, String descKey) throws Exception {
        if (StringUtils.isBlank(langKey)) langKey = getInitLang();
        System.out.println(initLang.toString());
        JSONObject jo = langItemMap.get(langKey);
        return jo.getString(descKey);
    }

    public void init() {
        initLangMap();
    }

    @Override
    public void run(String... args) throws Exception {
        initLangMap();
    }

    public void initLangMap() {
        System.out.println("==============================================initLangMap===================================================");
        String projectPath = apiConfig.getProjectPath() + "/Lang/";
        langItemMap = new HashMap<>();
        try {
            String langJsonFile = projectPath + "/lang.json";
            File file = new File(langJsonFile);
            String langTypeStr = FileUtils.readFileToString(file, charsetName);
            JSONObject jo = strToJSONObject(langTypeStr, null);
            System.out.println(jo.keySet().stream().findFirst());

            for (String key : jo.keySet()) {
                File langFile = new File(projectPath + jo.getString(key));
                String langStr = FileUtils.readFileToString(langFile, charsetName);
                JSONObject itemJo = strToJSONObject(langStr, null);
                langItemMap.put(key, itemJo);
            }
        } catch (FileNotFoundException fileNotFoundException) {
            log.error(fileNotFoundException.getMessage());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * JSONObject数组合并，同key后者会替换前者
     *
     * @param jsonObjects JSONObject数组列
     * @return 合并后JSON
     */
    private JSONObject jsonMerge(JSONObject... jsonObjects) {
        JSONObject rjo = new JSONObject();
        for (JSONObject joItem : jsonObjects) {
            for (String key : joItem.keySet()) {
                rjo.put(key, joItem.get(key));
            }
        }
        return rjo;
    }

    /**
     * String 转 JSONObject
     *
     * @param str
     * @param parKey
     * @return
     */
    private JSONObject strToJSONObject(String str, String parKey) {
        JSONObject rJsonO = new JSONObject();

        parKey = StringUtils.isBlank(parKey) ? "" : (parKey + ".");

        JSONObject jsonObject = JSONObject.parseObject(str);
        for (String key : jsonObject.keySet()) {
            String itemKey = parKey + key;
            String itemValue = jsonObject.getString(key);
            try {
                Object o = JSON.parse(itemValue);
                if (o instanceof JSONObject) {
                    ;
                    rJsonO = jsonMerge(rJsonO, strToJSONObject(itemValue, itemKey));
                }
                ;
            } catch (Exception e) {
                rJsonO.put(itemKey, itemValue);
            }
        }
        return rJsonO;
    }

}
